import axios from 'axios'
import { setRSApass } from './JSEncrypt'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'



// create an axios instance
const service = axios.create({
  headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (config.data) {
      setConsole(JSON.stringify(config.data))
      var data = setRSApass(JSON.stringify(config.data))
      config.data = JSON.stringify({ "data": data, token: getToken() })
      setConsole(config.data)
    } else {
      config.data = JSON.stringify(config.data)
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
function setConsole(data) {
  if (process.env.NODE_ENV !== 'production') {
    console.log(data)
  }
}
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.errorCode !== 200) {
      Message({
        message: res.errorMessage || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      if (res.errorCode === 407 || res.errorCode === 405) {
        MessageBox.confirm('您已经注销，您可以取消停留在本页，或再次登录，确认注销', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      } else if (res.errorCode === 509) {
        return response
      } else {
        return Promise.reject(new Error(res.errorMessage || 'Error'))
      }
    } else {
      return response
    }
  }
)


export default service
